import React from 'react';
import { Row, Col, Card, Tabs, DatePicker, Select, Button } from 'antd';
import { connect } from 'dva';
import ReactEcharts from 'echarts-for-react';
import numeral from 'numeral';
import styles from './Analysis.less';

const { RangePicker } = DatePicker;
const { TabPane } = Tabs;
const { Option } = Select;

@connect(({ report }) => ({
  report,
}))
class ReportCard extends React.Component {
  state = {
    selectValues: ['全部'],
  };

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'report/getReportCodeAndName',
    });
  }

  getCountOption = graphData => {
    if (graphData === undefined || graphData === null || graphData.length === 0)
      return {
        title: {
          text: '请求数统计图',
        },
        tooltip: {
          trigger: 'axis',
        },
        xAxis: [
          {
            type: 'category',
            boundaryGap: false,
            data: [],
          },
        ],
        yAxis: [
          {
            type: 'value',
          },
        ],
        series: [],
      };
    const legendData = new Set();
    const xAxisData = new Set();
    const seriesData = new Map();

    const recodeIndex = new Map();
    let index = 0;

    graphData.map(item => {
      legendData.add(item.name);
      if (!xAxisData.has(item.runDate)) {
        xAxisData.add(item.runDate);
        recodeIndex.set(item.runDate, index);
        index += 1;
      }
      return null;
    });
    graphData.map(item => {
      if (seriesData.get(item.name) === undefined) {
        const newArr = [];
        for (let i = 0; i < xAxisData.size; i += 1) {
          newArr.push(0);
        }
        seriesData.set(item.name, newArr);
      }
      const nowArr = seriesData.get(item.name);
      nowArr[recodeIndex.get(item.runDate)] = item.totalCount;
      return null;
    });
    return {
      title: {
        text: '请求数统计图',
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross',
          label: {
            backgroundColor: '#6a7985',
          },
        },
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '10%',
        containLabel: true,
      },
      legend: {
        type: 'scroll',
        data: Array.from(legendData),
        bottom: 0,
      },
      xAxis: {
        type: 'category',
        data: Array.from(xAxisData),
      },
      yAxis: {
        type: 'value',
        axisLabel: { formatter: '{value} 次' },
      },
      series: Array.from(legendData).map(item => {
        return {
          name: item,
          type: 'line',
          data: seriesData.get(item),
        };
      }),
    };
  };

  getAvgTimeOption = graphData => {
    if (graphData === undefined || graphData === null || graphData.length === 0)
      return {
        title: {
          text: '平均执行时间图',
        },
        tooltip: {
          trigger: 'axis',
        },
        xAxis: [
          {
            type: 'category',
            boundaryGap: false,
            data: [],
          },
        ],
        yAxis: [
          {
            type: 'value',
          },
        ],
        series: [],
      };
    const legendData = new Set();
    const xAxisData = new Set();
    const seriesData = new Map();

    const recodeIndex = new Map();
    let index = 0;

    graphData.map(item => {
      legendData.add(item.name);
      if (!xAxisData.has(item.runDate)) {
        xAxisData.add(item.runDate);
        recodeIndex.set(item.runDate, index);
        index += 1;
      }
      return null;
    });
    graphData.map(item => {
      if (seriesData.get(item.name) === undefined) {
        const newArr = [];
        for (let i = 0; i < xAxisData.size; i += 1) {
          newArr.push(0);
        }
        seriesData.set(item.name, newArr);
      }
      const nowArr = seriesData.get(item.name);
      nowArr[recodeIndex.get(item.runDate)] = item.avgTime;
      return null;
    });
    return {
      title: {
        text: '平均执行时间图',
      },
      tooltip: {
        trigger: 'axis',
        formatter: params => {
          let relVal = params[0].name;
          for (let i = 0, l = params.length; i < l; i += 1) {
            relVal += `<br/>${params[i].seriesName} : ${numeral(params[i].value).format('0,0')}ms`;
          }
          return relVal;
        },
        axisPointer: {
          type: 'cross',
          label: {
            backgroundColor: '#6a7985',
          },
        },
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '10%',
        containLabel: true,
      },
      legend: {
        type: 'scroll',
        data: Array.from(legendData),
        bottom: 0,
      },
      xAxis: {
        type: 'category',
        data: Array.from(xAxisData),
      },
      yAxis: {
        type: 'value',
        axisLabel: { formatter: '{value} ms' },
      },
      series: Array.from(legendData).map(item => {
        return {
          name: item,
          type: 'line',
          data: seriesData.get(item),
        };
      }),
    };
  };

  handleSelectChange = value => {
    this.setState({
      selectValues: value,
    });
  };

  render() {
    const { selectValues } = this.state;
    const {
      rangePickerValue,
      countData,
      avgTimeData,
      isActive,
      handleRangePickerChange,
      loading,
      selectDate,
      handleSearch,
      topCount,
      topAvgTime,
    } = this.props;
    const {
      report: { reportCodeAndName: allReportCodeAndName },
    } = this.props;
    return (
      <Card loading={loading} bordered={false} bodyStyle={{ padding: 0 }}>
        <div className={styles.salesCard}>
          <Tabs
            tabBarExtraContent={
              <div className={styles.salesExtraWrap}>
                <div className={styles.salesExtra}>
                  <a className={isActive('week')} onClick={() => selectDate('week')}>
                    本周
                  </a>
                  <a className={isActive('last week')} onClick={() => selectDate('last week')}>
                    上周
                  </a>
                  <a className={isActive('month')} onClick={() => selectDate('month')}>
                    本月
                  </a>
                </div>
                <RangePicker
                  value={rangePickerValue}
                  onChange={handleRangePickerChange}
                  style={{ width: 300 }}
                />
                <Select
                  defaultValue={selectValues}
                  style={{ marginLeft: 10, width: 280 }}
                  mode="multiple"
                  onChange={this.handleSelectChange}
                  maxTagCount={1}
                >
                  <Option value="全部">全部</Option>
                  {allReportCodeAndName &&
                    allReportCodeAndName.map(item => {
                      return (
                        <Option value={item.code} key={item.code}>
                          {item.name}
                        </Option>
                      );
                    })}
                </Select>
                <Button
                  type="text"
                  style={{ marginLeft: 10 }}
                  onClick={() =>
                    handleSearch({
                      codes: selectValues,
                      start: rangePickerValue[0].format('YYYY-MM-DD'),
                      end: rangePickerValue[1].format('YYYY-MM-DD'),
                    })
                  }
                >
                  查询
                </Button>
              </div>
            }
            size="large"
            tabBarStyle={{ marginBottom: 24 }}
          >
            <TabPane tab="请求数" key="sales">
              <Row>
                <Col xl={16} lg={12} md={12} sm={24} xs={24}>
                  <div className={styles.salesBar}>
                    <ReactEcharts
                      option={this.getCountOption(countData)}
                      notMerge
                      style={{ height: '370px', width: '100%' }}
                    />
                  </div>
                </Col>
                <Col xl={8} lg={12} md={12} sm={24} xs={24}>
                  <div className={styles.salesRank}>
                    <h4 className={styles.rankingTitle}>报表请求次数排名</h4>
                    <ul className={styles.rankingList}>
                      {topCount &&
                        topCount.map((item, i) => (
                          <li key={item.name}>
                            <span
                              className={`${styles.rankingItemNumber} ${
                                i < 3 ? styles.active : ''
                              }`}
                            >
                              {i + 1}
                            </span>
                            <span className={styles.rankingItemTitle} title={item.name}>
                              {item.name}
                            </span>
                            <span className={styles.rankingItemValue}>{item.totalCount}</span>
                          </li>
                        ))}
                    </ul>
                  </div>
                </Col>
              </Row>
            </TabPane>
            <TabPane tab="平均时间" key="views">
              <Row>
                <Col xl={16} lg={12} md={12} sm={24} xs={24}>
                  <div className={styles.salesBar}>
                    <ReactEcharts
                      option={this.getAvgTimeOption(avgTimeData)}
                      notMerge
                      style={{ height: '370px', width: '100%' }}
                    />
                  </div>
                </Col>
                <Col xl={8} lg={12} md={12} sm={24} xs={24}>
                  <div className={styles.salesRank}>
                    <h4 className={styles.rankingTitle}>报表请求时间排名</h4>
                    <ul className={styles.rankingList}>
                      {topAvgTime &&
                        topAvgTime.map((item, i) => (
                          <li key={item.name}>
                            <span
                              className={`${styles.rankingItemNumber} ${
                                i < 3 ? styles.active : ''
                              }`}
                            >
                              {i + 1}
                            </span>
                            <span className={styles.rankingItemTitle} title={item.name}>
                              {item.name}
                            </span>
                            <span className={styles.rankingItemValue}>
                              {numeral(item.avgTime).format('0,0')}ms
                            </span>
                          </li>
                        ))}
                    </ul>
                  </div>
                </Col>
              </Row>
            </TabPane>
          </Tabs>
        </div>
      </Card>
    );
  }
}

export default ReportCard;
